package com.example.newnoke.fragment.main;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.bumptech.glide.Glide;
import com.example.newnoke.R;
import com.example.newnoke.adapter.CommonAdapter;
import com.example.newnoke.adapter.LineChartEntity;
import com.example.newnoke.adapter.NewMarkerView;
import com.example.newnoke.adapter.ViewHolder;
import com.example.newnoke.data.BannerData;
import com.example.newnoke.data.LklListData;
import com.example.newnoke.data.NoticeData;
import com.example.newnoke.data.OrderData;
import com.example.newnoke.data.PayData;
import com.example.newnoke.data.QXData;
import com.example.newnoke.data.RealListEntity;
import com.example.newnoke.data.YoyListEntity;
import com.example.newnoke.data.ZcbListData;
import com.example.newnoke.databinding.FragmentQklBinding;
import com.example.newnoke.mvp.presenter.ZcPresenter;
import com.example.newnoke.mvp.view.IZcV;
import com.example.newnoke.payment.Payment;
import com.example.newnoke.ui.SucceedActivity;
import com.example.newnoke.utils.API;
import com.example.newnoke.view.dialog.PayDialgo;
import com.geya.jbase.basefragment.BaseDetailsFragment;
import com.geya.jbase.constant.RequestType;
import com.geya.jbase.uiview.LoadDialog;
import com.geya.jbase.uiview.ToastUtil;
import com.github.mikephil.chart_3_0_1v.charts.LineChart;
import com.github.mikephil.chart_3_0_1v.components.AxisBase;
import com.github.mikephil.chart_3_0_1v.components.Legend;
import com.github.mikephil.chart_3_0_1v.data.Entry;
import com.github.mikephil.chart_3_0_1v.data.LineDataSet;
import com.github.mikephil.chart_3_0_1v.formatter.IAxisValueFormatter;
import com.github.mikephil.chart_3_0_1v.formatter.IValueFormatter;
import com.github.mikephil.chart_3_0_1v.utils.ViewPortHandler;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Administrator on 2018/5/22 0022.
 */

public class QklFragment extends BaseDetailsFragment<ZcPresenter> implements IZcV, OnRefreshListener, OnLoadMoreListener {

    private FragmentQklBinding mBinding;
    private int start = 1;

    @Override
    public ZcPresenter newPresenter() {
        return new ZcPresenter(this);
    }

    @Override
    public int inflateCreateView() {
        return R.layout.fragment_qkl;
    }

    @Override
    public void initDatas(View view) {
        mBinding = DataBindingUtil.bind(view);
        mBinding.swipeToLoadLayout.setOnRefreshListener(this);
        //为swipeToLoadLayout设置上拉加载更多监听者
        mBinding.swipeToLoadLayout.setOnLoadMoreListener(this);
        HashMap<String, String> map = new HashMap<>();
        map.put("start", start + "");//&start=1&limit=10
        map.put("limit", "10");//&start=1&limit=10
        map.put("type", "1");//&start=1&limit=10
        mPresenter.accessServers(RequestType.OKGO_POST, API.ORDER, OrderData.class, map);
        HashMap<String, String> map2 = new HashMap<>();
        mPresenter.accessServers(RequestType.OKGO_POST, API.NOKE_TREND, QXData.class, map2);
//        initAdapter();
//        initDLinehartData();
    }

    @Override
    protected void onFragmentStartLazy() {
        super.onFragmentStartLazy();


        mPresenter.accessServers(RequestType.OKGO_POST, API.LKL, LklListData.class, null);
    }

    //----------------------------图标相关
    private DecimalFormat mFormat;

    public void initDLinehartData(List<QXData.DataBean.ListBean> list){

        mFormat = new DecimalFormat("#,###.##");
        List<YoyListEntity> yoyList = new ArrayList<>();
//          yoyList.add(new YoyListEntity("2018","11","0.1"));
//          yoyList.add(new YoyListEntity("2018","11","0.2"));
//          yoyList.add(new YoyListEntity("2018","11","0.3"));
//          yoyList.add(new YoyListEntity("2018","11","0.4"));
//          yoyList.add(new YoyListEntity("2018","11","0.5"));
//          yoyList.add(new YoyListEntity("2018","11","0.6"));
//          yoyList.add(new YoyListEntity("2018","11","1.2"));
        List<RealListEntity> realList = new ArrayList<>();


        int[] callDurationColors = {Color.parseColor("#45A2FF"), Color.parseColor("#5fd1cc")};
        Drawable[] drawables = {
                ContextCompat.getDrawable(getActivity(), R.drawable.chart_thisyear_blue),
                ContextCompat.getDrawable(getActivity(), R.drawable.chart_callserice_call_casecount)
        };
        List<Entry> values1 = new ArrayList<>();
//        values1.add(new Entry(2f,0.1f));
//        values1.add(new Entry(4f,0.2f));
//        values1.add(new Entry(6f,0.3f));
//        values1.add(new Entry(8f,0.4f));
//        values1.add(new Entry(10f,0.5f));
//        values1.add(new Entry(12f,0.6f));
//        values1.add(new Entry(14f,1.2f));


        for (int i = 0; i < list.size(); i++) {
            String[] arr = list.get(i).getCdate().split("-");
            if (i==0){
//                yoyList.add(new YoyListEntity(arr[0]+"."+arr[1],arr[2],list.get(i).getPrice()));
                yoyList.add(new YoyListEntity(arr[0],arr[1],arr[2],list.get(i).getPrice()));
            }else {
//                yoyList.add(new YoyListEntity(arr[0]+"."+arr[1],arr[2],list.get(i).getPrice()));
                yoyList.add(new YoyListEntity(arr[0],arr[1],arr[2],list.get(i).getPrice()));
            }

            values1.add(new Entry(Float.valueOf(arr[2]),Float.valueOf(list.get(i).getPrice())));
        }


        List<Entry> values2 = new ArrayList<>();

        String thisYear = "";
        if (realList.size() > 0) {
            thisYear = realList.get(0).getYear();
        }

        String lastYear = "";
        if (yoyList.size() > 0) {
            lastYear = yoyList.get(0).getYear();
        }

        String[] labels = new String[]{thisYear, lastYear};

        updateLinehart(yoyList,realList,
                mBinding.newLineChart,
                callDurationColors,
                drawables,
                "",
                 values1,values2,
                labels
                );
    }

    /**
     * 双平滑曲线传入数据，添加markview，添加实体类单位
     *
     * @param yoyList
     * @param realList
     * @param lineChart
     * @param colors
     * @param drawables
     * @param unit
     * @param values2
     * @param values1
     * @param labels
     */
    private void updateLinehart(final List<YoyListEntity> yoyList, final List<RealListEntity> realList, LineChart lineChart, int[] colors, Drawable[] drawables,
                                final String unit, List<Entry> values2, List<Entry> values1, final String[] labels) {


        List<Entry>[] entries = new ArrayList[2];
        entries[0] = values1;
        entries[1] = values2;
        LineChartEntity lineChartEntity = new LineChartEntity(lineChart, entries, labels, colors, Color.parseColor("#999999"), 12f);
        lineChartEntity.drawCircle(true);
        lineChart.setScaleMinima(1.0f, 1.0f);
        toggleFilled(lineChartEntity, drawables, colors);

        /**
         * 这里切换平滑曲线或者折现图
         */
//        lineChartEntity.setLineMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineChartEntity.setLineMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        lineChartEntity.initLegend(Legend.LegendForm.CIRCLE, 12f, Color.parseColor("#999999"));
        lineChartEntity.updateLegendOrientation(Legend.LegendVerticalAlignment.TOP, Legend.LegendHorizontalAlignment.RIGHT, Legend.LegendOrientation.HORIZONTAL);
        lineChartEntity.setAxisFormatter(
                new IAxisValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                        if (value == 1.0f) {

                            return mFormat.format(value) + "日";
                        }
                        String monthStr = mFormat.format(value);
                        if (monthStr.contains(".")) {
                            return "";
                        } else {
                            return monthStr;//横排日期
                        }
//                        return mMonthFormat.format(value);
                    }
                },
                new IAxisValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                        return mFormat.format(value) + unit;
                    }
                });

        lineChartEntity.setDataValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return mFormat.format(value) + unit;
            }
        });

        final NewMarkerView markerView = new NewMarkerView(getActivity(), R.layout.custom_marker_view_layout);
        markerView.setCallBack(new NewMarkerView.CallBack() {
            @Override
            public void onCallBack(float x, String value) {

                int index = (int) (x);
                if (index < 0) {
                    return;
                }

                for (YoyListEntity entity : yoyList) {
                    if (entity.getDay().equals(index+"".trim())) {
                        markerView.getTvContent().setText(entity.getMonth()+"."+entity.getDay()+"   "+entity.getAmount());
                    }
                }

//                if (index > yoyList.size() && index > realList.size()) {
//
//
//                    return;
//                }
//                String textTemp = "";
//
//                if (index <= yoyList.size()) {
//                    if (!StringUtils.isEmpty(textTemp)) {
//                    }
//                    textTemp += yoyList.get(index - 1).getYear() + "." + index + "  " + mFormat.format(Float.parseFloat(yoyList.get(index - 1).getAmount())) + unit;
//                }
//
//                if (index <= realList.size()) {
//                    textTemp += "\n";
//                    textTemp += realList.get(index - 1).getYear() + "." + index + "  " + mFormat.format(Float.parseFloat(realList.get(index - 1).getAmount())) + unit;
//                }
//                markerView.getTvContent().setText(textTemp);
            }
        });
        lineChartEntity.setMarkView(markerView);
        lineChart.getData().setDrawValues(false);
    }

    /**
     * 双平滑曲线添加线下的阴影
     *
     * @param lineChartEntity
     * @param drawables
     * @param colors
     */
    private void toggleFilled(LineChartEntity lineChartEntity, Drawable[] drawables, int[] colors) {
        if (android.os.Build.VERSION.SDK_INT >= 18) {

            lineChartEntity.toggleFilled(drawables, null, true);
        } else {
            lineChartEntity.toggleFilled(null, colors, true);
        }
    }

    //------------------------------------------------------------


    @Override
    public void onRefresh() {
        start = 1;
        HashMap<String, String> map = new HashMap<>();
        map.put("start", start + "");
        map.put("limit", "10");
        map.put("type", "1");
        mPresenter.accessServers(RequestType.OKGO_POST, API.ORDER, OrderData.class, map);

        HashMap<String, String> map2 = new HashMap<>();
        mPresenter.accessServers(RequestType.OKGO_POST, API.NOKE_TREND, QXData.class, map2);
    }

    @Override
    public void onLoadMore() {
        start++;
        HashMap<String, String> map = new HashMap<>();
        map.put("start", start + "");
        map.put("limit", "10");
        map.put("type", "1");
        mPresenter.accessServers(RequestType.OKGO_POST, API.ORDER, OrderData.class, map);

    }


    private CommonAdapter<OrderData.DataBean> adapter;
    private List<OrderData.DataBean> mList = new ArrayList<>();

    @Override
    public void setListAdapter(List<OrderData.DataBean> list) {
        if (start==1){
            mList.clear();
        }
        mList.addAll(list);
        if (adapter == null) {
            adapter = new CommonAdapter<OrderData.DataBean>(getActivity(), mList, R.layout.item_list_qkl_record) {
                @Override
                public void convert(ViewHolder holder, OrderData.DataBean s, int position) {
                    holder.setText(R.id.name,s.getInputtime())
                            .setText(R.id.num,s.getTotal_num()+"")
                            .setText(R.id.price,s.getTotal_price()+"")
                            .setText(R.id.type,s.getStatus()==1?"已完成":"未支付");
                }
            };
            mBinding.list.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }

        mBinding.swipeToLoadLayout.setRefreshing(false);
        mBinding.swipeToLoadLayout.setLoadingMore(false);
    }

    @Override
    public void pay(String s, final String order) {
        Payment mPayment = new Payment(getActivity());
        mPayment.setOnPayResult(new Payment.onPayResult() {
            @Override
            public void onSucceed() {
                startActivity(new Intent(getActivity(),SucceedActivity.class)
                        .putExtra("id",order)
                );
                ToastUtil.showShort("支付成功");
            }

            @Override
            public void onError() {
                ToastUtil.showShort("支付失败");
            }
        });
        mPayment.alipay(s);
    }

    @Override
    public void qxList(List<QXData.DataBean.ListBean> list) {
        initDLinehartData(list);
    }

    @Override
    public void setDatas(QXData.DataBean data) {
        mBinding.gujia.setText("￥ "+data.getStock());
        mBinding.num.setText(data.getNoke_coin()+" 个");
        mBinding.jiazhi.setText("￥ "+data.getValue());
    }

    @Override
    public void setBanner(List<BannerData.DataBean> list) {

    }

    @Override
    public void setZcbList(List<ZcbListData.DataBean> list) {

    }

    @Override
    public void setLklList(final List<LklListData.DataBean> list) {
         CommonAdapter<LklListData.DataBean> adapter = new CommonAdapter<LklListData.DataBean>(getActivity(),list,R.layout.item_img) {
             @Override
             public void convert(ViewHolder holder, LklListData.DataBean dataBean, int position) {
                 Glide.with(getActivity())
                         .load(RequestType.ADDRESS+dataBean.getThumb())
                         .into((ImageView) holder.getView(R.id.tv_img));

             }
         };
         mBinding.lklList.setAdapter(adapter);
         mBinding.lklList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                 PayDialgo dialgo = new PayDialgo();
                 Bundle bundle = new Bundle();
                 bundle.putString("name",list.get(position).getName() );
                 bundle.putString("price",list.get(position).getPrice() +"".trim());
                 bundle.putString("id",list.get(position).getId() + " ");
                 bundle.putString("type","1");

                 dialgo.setArguments(bundle);
                 dialgo.show(getActivity().getSupportFragmentManager(), new PayDialgo.PayCallBack() {
                     @Override
                     public void pay(String s1, String s2, String s3, String s4, String s5,String id) {
                         LoadDialog.show(getActivity());
                         HashMap<String, String> map = new HashMap<>();
                         map.put("type", "1");
                         map.put("goods_name", s2);
                         map.put("goods_id", id);
                         map.put("total_num", s3);
                         map.put("price", s4);//
                         map.put("payway", "1");

                         mPresenter.accessServers(RequestType.OKGO_POST, API.PAY, PayData.class, map);
                     }

//                    @Override
//                    public void pay() {
//                        HashMap<String, String> map = new HashMap<>();
//                        map.put("type", "2");
//                        map.put("goods_name", "测试商品");
//                        map.put("price", "2000");
//                        map.put("total_num", "1");
//                        map.put("payway", "1");
//
//                        mPresenter.accessServers(RequestType.OKGO_POST, API.PAY, BaseDatas.class, map);
//                    }

                 });
             }
         });
    }

    @Override
    public void initFlipper(List<NoticeData.DataBean> list) {
        
    }
}
